#include "vtps.h"
#include "vlog.h"
#include <iomanip>

vtps::vtps()
{
}

vtps::~vtps()
{

}


unsigned long long vtps::tps(const std::string & name)
{
    std::lock_guard<std::mutex> _lock(_mutex);
    return _map_name_msg[name].tps();
}

//void vtps::start(const std::string & name)
//{
//    _map_name_msg[name].elapsed(_ct.elapsed().wall);
//    _map_name_msg[name].tps(); //set _last variable
//}
//
//void vtps::stop(const std::string & name)
//{
//   _map_name_msg[name].elapsed(_ct.elapsed().wall);
//}

void vtps::clear(const std::string & name)
{
    std::lock_guard<std::mutex> _lock(_mutex);
    _map_name_msg.erase(name);
}

void vtps::clear()
{
    std::lock_guard<std::mutex> _lock(_mutex);
    _map_name_msg.clear();
}

void vtps::increase(const std::string & name,
                bool auto_log,
                unsigned int interval) //unit:ms
{
    std::lock_guard<std::mutex> _lock(_mutex);
    auto & msg_meta = _map_name_msg[name];
    msg_meta.increase_count();

    if(auto_log && interval > 0)
    {
        if(msg_meta.elapsed() >= static_cast<unsigned long long>(interval))
        {
            vlogi<<std::setw(8)<<name<<" is:"
                <<std::setw(5)<<msg_meta.tps()<<" t/s"<<std::endl;
        }
    }
}

void vtps::increase(unsigned long long byte_count,
                const std::string & name, 
                bool auto_log,
                unsigned int interval) //unit:ms
{
    std::lock_guard<std::mutex> _lock(_mutex);
    auto & msg_meta = _map_name_msg[name];
    msg_meta.increase_count(byte_count);

    if(auto_log && interval > 0)
    {
        if(msg_meta.elapsed() >= static_cast<unsigned long long>(interval))
        {
            auto tps = msg_meta.tps();
            std::string tps_str;
            
            if(tps<1024)
            {
                //do nothing
               tps_str =  "0 kb/s";
            }
            else if(tps>=1024 && tps<1024*1024)
            {
               tps_str =  std::to_string(tps/1024)+" kb/s";
            }
            else if(tps>=1024*1024 && tps < 1024*1024*1024)
            {
               tps_str =  std::to_string(tps/(1024*1024))+" mb/s";
            }
            else  
            {
               tps_str =  std::to_string(tps/(1024*1024*1024))+" gb/s";
            }

            vlogi<<std::setw(8)<<name<<" is:"
                <<std::setw(8)<<tps<<" byte/s,"
                <<std::setw(8)<<tps_str
                <<std::endl;
        }
    }
}


